/***************************************** 
 *
 * Listing 1.2
 *
 * Example performing I/O on s socket pair:
 * 
 * ******************************************/ 
#include "channel.h"

int httpd_write_channel(int sock, http_channel_t *send_buf, int send_len)
{
    struct msghdr msg;
    struct iovec iov[1];        
    
    bzero(&msg, sizeof(msg));
    msg.msg_name = NULL;        /* attention this is a pointer to void* type */
    msg.msg_namelen = 0;         
        
    iov[0].iov_base = send_buf;
    iov[0].iov_len = send_len;
    
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;        

    sendmsg( sock, &msg, 0 );
    return 0;
}


int httpd_read_channel(int sock, http_channel_t *recv_buf, int recv_len)
{
    struct msghdr msgr;
    struct iovec iovr[1];      
      
    bzero(&msgr, sizeof(msgr));
    bzero(recv_buf, sizeof(recv_buf));
    
    msgr.msg_name = NULL;        // attention this is a pointer to void* type
    msgr.msg_namelen = 0;
        
    iovr[0].iov_base = (char*) recv_buf;
    iovr[0].iov_len = recv_len;
    
    msgr.msg_iov = iovr;    
    msgr.msg_iovlen = 1; 
    
    recvmsg(  sock, &msgr, 0);
    
    return 0;               
}

#if 0
int main(int argc,char **argv)
{
    int z;        /* Status return code */
    int s[2];    /* Pair of sockets */
    int status;       

    /*
     * Create a pair of local sockets:
     */
    z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);

    if(z == -1) {
        fprintf(stderr,
                "%s:socketpair(AF_LOCAL,SOCK_STREAM,""0)\n",strerror(errno));
        return 1;    /* Failed */
    }
    
    pid_t pid = fork();

    if (pid>0) {//parent    
        /*
        * Sendmsg to Socket s[1]:
        */            
        char send_buf[100] = "abcdefghijk";
        printf("sendmsg begin.\n");
        z = httpd_write_channel(s[0], send_buf, strlen(send_buf));
        
        if(z == -1 ) {
            fprintf(stderr,"Sendmsg failed.  errno : %s\n",strerror(errno));
            return -1;
        }
        printf("Sendmsg Success!\n");
        //close(s[1]);
                        
        wait( &status );
        puts("Done");
    }
    else if (pid==0) {//son                
        /*
         * Read from socket s[0]:
         */        
        char recv_buf[100];
        
        z = httpd_read_channel(s[1], recv_buf, sizeof(recv_buf));        
        if(z == -1 ) {
            fprintf(stderr,"Recvmsg failed.  errno : %s\n",strerror(errno));
            return -1;
        }
        
        printf("Recvmsg Success!\n");
        printf("recvmsg : %s, size : %d\n", recv_buf, sizeof(recv_buf) );    

        //close(s[0]);
    }
    else {
        printf("Fork error!\n");
    }

    return 0;
}
#endif
